import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

// 动态解析当前路由模块下的文件
const importFile = require.context("@/router", false, /\.js$/);
const lib = importFile.keys();
const fileObj = {};
// 动态导入路由文件
function importAll(r) {
  r.keys().forEach((key) => {
    fileObj[key] = r(key).default;
  });
}
importAll(importFile);
const routerArry = lib.filter((file) => {
  return file !== "./index.js";
});
// console.log(routeList)
const routeList = [];
routerArry.forEach((routerItem) => {
  routeList.push(fileObj[routerItem]);
});
const routes = routeList.flat();
// console.log(routes)
// 主应用登录拦截

const router = new VueRouter({
  mode: "hash",
  routes,
});
let token = localStorage.getItem("ALB_H5_TOKEN");
router.beforeEach((to, from, next) => {
  if (token) {
    next();
  }
  // 防止next()死循环
  else {
    if (to.path == "/logon" || to.path == "/") {
      next();
    } else {
      next({
        path: "/logon",
      });
    }
  }
});
export default router;
